﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using API.Models;
using PPG.DataAccess;
using PPG.CryptoProvider;
using System.Xml;
using System.Data;
using System.Configuration;
using System.Web;
using System.Collections;


namespace API.Controllers
{
    public class FilterDiagnosisController : ApiController
    {
        DataSourceCommunicator dsComm = new DataSourceCommunicator(DataSourceCommunicator.ParamType.ServerCredentials, ConfigurationManager.AppSettings["DBServerName"].ToString(), ConfigurationManager.AppSettings["DBUserName"].ToString(), ConfigurationManager.AppSettings["DBPassword"].ToString());

        public AddReferralDiagonsisResponse FilteredDiagnosis([FromBody]FilterDiagnosisRequest request)
        {
            AddReferralDiagonsisResponse response = new AddReferralDiagonsisResponse();

            dsComm.AddParameter("@ParamReferralID", request.ReferralID);
            dsComm.AddParameter("@ParamSearchText", request.SearchText);
            string data = dsComm.ExecuteStoredProcedure("dbo.spGetFilteredDiagnosis");
            XmlTextReader xReader = new XmlTextReader(data, XmlNodeType.Document, null);
            DataSet DiagnosisDataSet = new DataSet();
            DiagnosisDataSet.ReadXml(xReader);

            if (DiagnosisDataSet.Tables.Count > 0)
            {
                response.PatientDiagnosis = DiagnosisDataSet.Tables[0];
                response.ErrorMessage = "Found Data";
                if (DiagnosisDataSet.Tables.Count > 1)
                {
                    ArrayList ls = new ArrayList();
                    DataTable tb = DiagnosisDataSet.Tables[1];
                    for (int i = 0; i < tb.Rows.Count; i++)
                    {
                        ls.Add(tb.Rows[i][0].ToString());
                    }

                    response.ChipData = ls.ToArray();
                }
            }
            else
            {
                response.PatientDiagnosis = new DataTable();
                response.ErrorMessage = "No Data";
            }
            return response;
        }

        /// <summary>
        /// Options response for the preflight request of a CORS Opertaions. Will be standard across various functions
        /// </summary>
        /// <returns></returns>
        public HttpResponseMessage OptionsPatientDiagnosis()
        {
            var response = new HttpResponseMessage();
            response.StatusCode = HttpStatusCode.OK;
            return response;
        }
    }
}
